let RouteModel = require('../model/ControllerModel')
const { userAPI } = require('../configure')

class Common extends RouteModel {

  constructor () {super()}

  // 获取省、市、区
  async getArea (ctx, next) {
    let query = ctx.query;
    let result;
    if (query.privonce) {
      result = await this.request({
        url: `${userAPI}/biz/city/${query.privonce}`
      }, ctx.query.traceId)
    } else if (query.city) {
      result = await this.request({
        url: `${userAPI}/biz/district/${query.city}`
      }, ctx.query.traceId)
    } else {
      result = await this.request({
        url: `${userAPI}/biz/privonce`
      }, ctx.query.traceId)
    }
    if (!result) return;
    let areaList = [], list;
    list = result.data.privonceList || result.data.cityList || result.data.districtList;
    list.forEach(item => {
      areaList.push({name: item.name, code: `{name: ${item.name}, code: ${item.code}}`, value: item.code})
    })
    result.data = areaList;
    ctx.$success(result)
  }

  // 获取省市区全量数据
  async getAreaAll (ctx, next) {
    let result = await this.request({
      url: `${userAPI}/biz/privonce`
    }, ctx.query.traceId)
    if (!result) return;
    let list = result.data.privonceList, areaList = [];
    list.forEach((privonce, privonceIndex) => {
      areaList.push({name: privonce.name, code: `{name: ${privonce.name}, code: ${privonce.code}}`, value: privonce.code, children: []})
      privonce.cityList.forEach((city, cityIndex) => {
        areaList[privonceIndex]['children'].push({name: city.name, code: `{name: ${city.name}, code: ${city.code}}`, value: city.code, children: []})
        city.districtList.forEach((district) => {
          areaList[privonceIndex]['children'][cityIndex]['children'].push({name: district.name, code: `{name: ${district.name}, code: ${district.code}}`, value: district.code,})
        })
      })
    })
    result.data = areaList
    ctx.$success(result)
  }

  // 学段、学科
  async getDictionary (ctx, next) {
    let query = ctx.query, result;
    if (query.subjects) {  // 学科
      result = await this.request({
        url: `${userAPI}/biz/xueduan/${query.subjects}/xueke`
      }, ctx.query.traceId)
    } else { // 学段
      result = await this.request({
        url: `${userAPI}/biz/dictionary/xueduan`
      }, ctx.query.traceId)
    }
    if (!result) return;
    let data = result.data.dictionaryItemList || result.data;
    let list = [];
    data.forEach(item => {
      list.push({itemname: item.itemname, id: item.id})
    })
    result.data = list
    ctx.$success(result)
  }

}

module.exports = Common
